//
// Created by fazhehy on 2024/3/15.
//

#include "key.h"

#define KEY_1   P11_0
#define KEY_2   P11_1
#define KEY_3   P11_2
#define KEY_4   P10_3
#define KEY_5   P10_2

void key_init_hy()
{
    gpio_init(KEY_1, GPI, GPIO_HIGH, GPI_PULL_UP);
    gpio_init(KEY_2, GPI, GPIO_HIGH, GPI_PULL_UP);
    gpio_init(KEY_3, GPI, GPIO_HIGH, GPI_PULL_UP);
    gpio_init(KEY_4, GPI, GPIO_HIGH, GPI_PULL_UP);
    gpio_init(KEY_5, GPI, GPIO_HIGH, GPI_PULL_UP);
}

uint8_t get_key_num()
{
    bool isLongPressure = false;
    uint32_t tick = 0;
    uint8_t keyNum = 0;
    if (gpio_get_level(KEY_1) == 0){
        system_delay_ms(20);
        while (gpio_get_level(KEY_1) == 0){
            tick ++;
            system_delay_ms(1);
        }
        if (tick >= 500){
            isLongPressure = true;
        }
        system_delay_ms(20);
        if (!isLongPressure)
            keyNum = 1;
        else
            keyNum = 6;
    }
    if (gpio_get_level(KEY_2) == 0){
        system_delay_ms(20);
        while (gpio_get_level(KEY_2) == 0){
            tick ++;
            system_delay_ms(1);
        }
        if (tick >= 500){
            isLongPressure = true;
        }
        system_delay_ms(20);
        if (!isLongPressure)
            keyNum = 2;
        else
            keyNum = 7;
    }
    if (gpio_get_level(KEY_3) == 0){
        system_delay_ms(20);
        while (gpio_get_level(KEY_3) == 0){
            tick ++;
            system_delay_ms(1);
        }
        if (tick >= 500){
            isLongPressure = true;
        }
        system_delay_ms(20);
        if (!isLongPressure)
            keyNum = 3;
        else
            keyNum = 8;
    }
    if (gpio_get_level(KEY_4) == 0){
        system_delay_ms(20);
        while (gpio_get_level(KEY_4) == 0){
            tick ++;
            system_delay_ms(1);
        }
        if (tick >= 500){
            isLongPressure = true;
        }
        system_delay_ms(20);
        if (!isLongPressure)
            keyNum = 4;
        else
            keyNum = 9;
    }
    if (gpio_get_level(KEY_5) == 0){
        system_delay_ms(20);
        while (gpio_get_level(KEY_5) == 0){
            tick ++;
            system_delay_ms(1);
        }
        if (tick >= 500){
            isLongPressure = true;
        }
        system_delay_ms(20);
        if (!isLongPressure)
            keyNum = 5;
        else
            keyNum = 10;
    }
    return keyNum;
}
